<?php
declare (strict_types = 1);

namespace app\api\controller\customer;
use AlibabaCloud\SDK\Dingtalk\Vworkflow_1_0\Models\QuerySchemaByProcessCodeResponseBody\result\schemaContent\items\props\push;
use app\common\customer\model\Customer;
use app\common\customer\model\CustomerAllocate;
use app\common\customer\model\CustomerTag;
use app\common\customer\model\CustomerVisit;
use app\common\customer\validate\CustomerVisitValidate;
use app\api\controller\Api;
use think\Db;
use think\db\exception\DbException;

class Visit extends Api
{
    // 获取指定客资的回访列表
    public function index()
    {
        $post = $this->request->post();
        if (empty($post['member_id'])) return error([], "参数错误");

        $visitModel = new CustomerVisit();
        $list = $visitModel->where('member_id', $post['member_id'])->select();
        foreach ($list as $row) {
            $row->append(["user", "status_title"]);
        }

        $result = $list;
        return success($result);
    }

    // 创建回访
    public function create()
    {
        $post = $this->request->post();
        // 获取当前用户的信息
        $user = $this->request->user;

        // 验证回访信息
        $visitValidate = new CustomerVisitValidate();
        if (!$visitValidate->check($post)) return error([], $visitValidate->getError());

        $memberModel = new Customer();
        $member = $memberModel->where('id', $post['member_id'])->find();
        if (empty($member)) return error([], "客资不存在");

        $post['user_id'] = $user['id'];
        $model = new CustomerVisit();
        $model->startTrans();

        try {
            $model->save($post);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        try {
            // 同步客资回访次数及状态
            $data = [];
            $data['visit_times'] = $member->visit_times + 1;
            $data['status'] = $post['status'];

            $member->save($data);

            // 同步跟进的客资状态
            $updateWhere = [];
            $updateWhere['member_id'] = $post['member_id'];
            $updateWhere['user_id'] = $user['id'];
            $allocateModel = new CustomerAllocate();
            $allocate = $allocateModel->where($updateWhere)->find();

            // 同步跟进状态
            if (!empty($allocate)) {
                $data = [];
                $data['status'] = $post['status'];
                $data['visit_times'] = $allocate->visit_times + 1;
                $data['next_visit_time'] = $post['next_visit_time'];
                $allocate->save($data);
            }

            $model->commit();

        } catch (DbException $e) {
            $model->rollback();
            return error([], '回访次数追加失败, 回访失败');
        }

        return success([], "添加回访记录成功");
    }

    public function save() {
        $post = $this->request->post();
        // 获取当前用户的信息
        $user = $this->request->user;
        if (empty($post['id'])) {
            return error([], "参数错误");
        }

        // 验证回访信息
        $visitValidate = new CustomerVisitValidate();
        if (!$visitValidate->check($post)) return error([], $visitValidate->getError());

        $memberModel = new Customer();
        $member = $memberModel->where('id', $post['member_id'])->find();
        if (empty($member)) return error([], "客资不存在");

        // $post['user_id'] = $user['id'];
        $model = new CustomerVisit();
        $model->startTrans();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) {
            return error([], "当前回访数据已经不存在");
        }

        try {
            unset($post['create_time']);
            unset($post['update_time']);
            $row->save($post);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        try {
            // 同步客资回访次数及状态
            $data = [];
            $data['status'] = $post['status'];
            $member->save($data);

            // 同步跟进的客资状态
            $updateWhere = [];
            $updateWhere['member_id'] = $post['member_id'];
            $updateWhere['user_id'] = $user['id'];
            $allocateModel = new CustomerAllocate();
            $allocate = $allocateModel->where($updateWhere)->find();

            // 同步跟进状态
            if (!empty($allocate)) {
                $data = [];
                $data['status'] = $post['status'];
                $data['next_visit_time'] = $post['next_visit_time'];
                $data['overdue'] = 0;
                $allocate->save($data);
            }

            $model->commit();

        } catch (DbException $e) {
            $model->rollback();
            return error([], '回访次数追加失败, 回访失败');
        }

        return success([], "添加回访记录成功");
    }

    // 删除回访
    public function delete()
    {
        $post = $this->request->post();
        if (empty($post['id'])) return error([], "参数错误");

        // 验证权限
        $visitModel = new CustomerVisit();
        $visitModel->startTrans();
        $visit = $visitModel->where('id', $post['id'])->find();

        if ($visit->delete()) {
            CustomerTag::destroy(function ($query) use ($post){
                $query->where('visit_id', $post['id']);
            });
            $visitModel->commit();
            return success([], "删除成功");
        } else {
            $visitModel->rollback();
            return error([], "删除失败");
        }
    }


    public function group()
    {
        $post = $this->request->post();
        $memberId = $post['member_id'];

        $users = [];
        // 获取跟进记录
        $visitModel = new CustomerVisit();
        $visits = $visitModel->where('member_id', $memberId)->order('id desc')->select();
        foreach ($visits as $row) {
            $row->append(['user', 'status_title']);
            $userId = $row['user_id'];
            $nextVisitTime = $row->getData('next_visit_time');
            if (!isset($users[$userId])) {
                $users[$userId] = [];
            }
            array_push($users[$userId], date('Y-m-d', $nextVisitTime));
        }
        $result['visits'] = $visits;

        // 获取拥有者
        $allocateModel = new CustomerAllocate();
        $fields = ['id', 'from_user_id', 'user_id', 'visit_times', 'status', 'create_time', 'next_visit_time', 'sign_time'];
        $owners = $allocateModel->field($fields)->where('member_id', $memberId)
                ->order('visit_times desc,id desc')
                ->select();

        foreach ($owners as $row) {
            $row->append(['from_user', 'user', 'visit_status']);
            $userId = $row['user_id'];
            if (!empty($row['next_visit_time']) && isset($users[$userId])) {
                $visitTime = $row->getData('create_time');
                $arr = $users[$userId];
                // 判断$arr中的时间戳，是否存在和$isitTime在同一天的
                if (in_array(date('Y-m-d', $visitTime), $arr)) {
                    $row['is_visit'] = 1;
                } else {
                    $row['is_visit'] = 0;
                }
            } else {
                $row['is_visit'] = -1;
            }
        }
        $result['owners'] = $owners;



        return success($result);
    }
}
